<?php
namespace app\wap\controller;

use think\Controller;
use app\wap\model\Member;
use app\wap\model\Project;
use app\index\model\OrderProfit;
use app\index\model\Order as orders;
use app\firm\model\ProjectUser;
use think\Db;
use think\Request;
use expand\BestSignDemo;
use expand\Yunst;
use expand\YunPay;
use think\Config;
use app\index\model\Lookinto;

class Order extends Common
{
    public function _initialize(){
        parent::_initialize();

    }

    /**
     * 确认订单页面
     * @param Request $request
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function viewPreOrder(Request $request){
        if($request->isPost()) {
            $mModel = new Member();
            $pModel = new Project();
            $user_info = $request->user_info;
            $uid = $user_info['id'];
            $param = $request->param();
            $project_id = $param['project_id'];
            if(empty($uid) || empty($project_id)){
                outPutData('','参数错误,请重新刷新页面',Config::get('code.tipsCode'));
            }
            $project_info = $pModel->where(array('id'=>$project_id))->find();
            $project_info = empty($project_info)?array():$project_info->toArray();
            $my_money = $mModel->where(array('id'=>$uid))->value('money');
            if(empty($project_info)){
                outPutData('','未查询到项目信息',Config::get('code.tipsCode'));
            }

            $res_data=array('money'=>$my_money,'project_name'=>$project_info['project_name']);
            outPutData($res_data);

        }
    }

    /**
     * 确认支持,创建订单
     * @param Request $request
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function createOrder(Request $request){
        if($request->isPost()) {
            $user_info = $request->user_info;
            $uid = $user_info['id'];
            $lookModel = new Lookinto();
            $isLookInto = $lookModel->where(['uid'=>$uid])->field('create_time,score')->order('create_time desc')->limit(1)->find();
            $isLookInto = empty($isLookInto) ? array() : $isLookInto->toArray();
            if(empty($isLookInto) || ($isLookInto['score'] < LOOK_INTO_SORE)){
                outPutData('','您的投资类型评估不符合条件，请前往个人中心重新评估。',Config::get('code.tipsCode'));
            }

            $param = $request->param();
            $money = trim($param['money']);
            $project_id = $param['project_id'];

            if(empty($uid) || empty($project_id)){
                outPutData('','提交参数错误,请重新刷新页面',Config::get('code.tipsCode'));
            }
            $money = sprintf("%.2f",$money);
            if($money==0 || substr($money, 0, 1 )==0){
                outPutData('','请输入正确的大于0的整数',Config::get('code.tipsCode'));
            }
            if(($money%100)!=0){
                outPutData('','请输入100的整数倍',Config::get('code.tipsCode'));
            }
            $mModel = new Member();
            $pModel = new Project();
            $oModel = new orders();
            $opModel = new OrderProfit();
            $nowTime = time();
            $selfmoney = $mModel->where(['id'=>$uid])->value('money');
            $isCheck = $mModel->where(['id'=>$uid])->value('is_check');
            $parentId = $mModel->where(['id'=>$uid])->value('parentId');
            $subordinate_name = $mModel->where(['id'=>$uid])->value('username');
            if(!$isCheck){
                outPutData('','请先进行实名认证',Config::get('code.tipsCode'));
            }
            if($money > $selfmoney){
                outPutData('','账户余额不足',Config::get('code.tipsCode'));
            }

            $res=$pModel->where(['id'=>$project_id])->find()->toArray();
            if(empty($res)){
                outPutData('','项目信息查询为空',Config::get('code.tipsCode'));
            }
            $zuida=$res['target_code']; //项目目标金额
            $max=$res['max_code'];  //限制最大投资金额
            if($money>$max){
                outPutData('','投资大于最高投资金额',Config::get('code.tipsCode'));
            }
            $res=$oModel->where(['project_id'=>$project_id,'status'=>'1'])->select();
            $res = empty($res)?array():$res->toArray();
            $mo=0;
            foreach ($res as $v){
                $mo+=$v['money'];
            }
            $yue=$zuida-$mo;
            if($money>$yue){
                outPutData('','投资大于剩余投资金额',Config::get('code.tipsCode'));
            }
            $ProInfo = $pModel->where(['id'=>$project_id])->find();
            $hasMoney = GetProjectBar($project_id);
            $overMoney = $ProInfo['target_code'] - $hasMoney;
            $overMoney = sprintf("%.2f",$overMoney);
            if($money > $overMoney){
                outPutData('','最多可支持金额'.$overMoney.'元',Config::get('code.tipsCode'));
            }
            if($nowTime > $ProInfo['end_time']){
                outPutData('','时间已结束',Config::get('code.tipsCode'));
            }
            if($ProInfo['end_time'] == -1){
                outPutData('','项目已失败',Config::get('code.tipsCode'));
            }

            //创建支持订单
            $order = [
                'order_sn' => 'HRY'.create_order(),
                'uid' => $uid,
                'project_id' => $project_id,
                'money'	=> $money,
                'status' => 0,
                'type'=>1,
                'create_time'=> $nowTime
            ];
            //临时调整项目为不需要计算业绩以及佣金
//            if ($project_id == 28 || $project_id == 31 || $project_id==45) {
//                $order['transport'] = 1;
//            }
            if($ProInfo['is_count'] == 2){
                $order['transport'] = 1;
            }
            $order_id = $oModel->insertGetId($order);
            if(!$order_id){
                outPutData('',$oModel->getError(),Config::get('code.tipsCode'));
            }
            //订单代收
            $YunClass = new Yunst();
            $puModel = new ProjectUser();
            $bizUserId = $mModel->where(['id'=>$uid])->value('bizUserId');
            $pu_info = $puModel->where(['id'=>$ProInfo['initiator']])->find();
            $message = $YunClass->DanBiDaiShou($bizUserId,$pu_info['bizUserId'],$order);
            if($message['status'] != 'OK'){
                outPutData('',$message['message'],Config::get('code.tipsCode'));
            } else {
                if ($parentId && $ProInfo['commission_proportion']) {
                    $member_name = $mModel->where(['id'=>$parentId])->value('username');
                    $member_mobile = $mModel->where(['id'=>$parentId])->value('mobile');
                    $subordinate_order = [];
                    $subordinate_order['project_id'] = $project_id;
                    $subordinate_order['order_sn'] = $order['order_sn'];
                    $subordinate_order['payment_sn'] = 'HRY'.create_order();
                    $subordinate_order['member_id'] = $parentId;
                    $subordinate_order['member_name'] = $member_name;
                    $subordinate_order['member_mobile'] = $member_mobile;
                    $subordinate_order['subordinate_member_id'] = $uid;
                    $subordinate_order['subordinate_name'] = $subordinate_name;
                    $subordinate_order['order_money'] = $money;
                    $subordinate_order['money'] = $money * ($ProInfo['commission_proportion'] / 100);
                    $subordinate_order['create_time'] = time();
                    $order_profit_id = $opModel->insertGetId($subordinate_order);
                    if(!$order_profit_id){
                        $error['uid'] = $uid;
                        $error['order_sn'] =$order['order_sn'];
                        $error['error'] = '创建支持订单时,生成佣金订单出错';
                        file_put_contents(date("Y-m-d H:i").'wap_order_profit.txt',json_encode($error,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
                    }
                }
            }

            $res=array('order_id'=>$order_id,'order_sn'=>$order['order_sn'],'money'=>$money,'mobile'=>$user_info['mobile'],'time'=>date('Y-m-d H:i:s',time()));
            outPutData($res);
        }
    }

    /**
     * 付款页面
     * @param Request $request
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
     public function confirmPayOrder(Request $request){
         $pModel = new Project();
         $orModel = new Orders();
         $user_info = $request->user_info;
         $uid = $user_info['id'];
         $param = $request->param();
         if($request->isPost()) {
             if (empty($param['order_id']) || empty($param['code'])) {
                 outPutData('', '提交参数错误,请重新刷新页面', Config::get('code.tipsCode'));
             }
             $data = $orModel->where(['id' => $param['order_id'], 'uid' => $uid])->find();
             $data = empty($data) ? array() : $data->toArray();
             if (empty($data)) {
                 outPutData('', '未查询到订单信息', Config::get('code.tipsCode'));
             }
             $money = floatval($data['money']);
             $code = trim($param['code']);
             $proid = $data['project_id'];
             $pro = $pModel->where(['id' => $proid])->find()->toArray();
             $status = $pro['status'];
             if ($status == 3) {
                 outPutData('', '该项目已经完成所有认投,敬请期待下个项目', Config::get('code.tipsCode'));
             }
             $summoney = $orModel->where(['status' => 2, 'type' => 1, 'project_id' => $proid])->sum('money');
             $sum = ($money + $summoney);
             $maxmoney = floatval($pro['target_code']);
             $sum = intval(($sum * 100));
             $maxmoney = intval(($maxmoney * 100));
             if ($sum > $maxmoney) {
                 outPutData('', '本次投资金额超过剩余可投金额', Config::get('code.tipsCode'));
             }
             $payClass = new Yunst();
             $mModel = new Member();
             $bizUserId = $mModel->where(['id' => $uid])->value('bizUserId');
             $res = $payClass->balancePay($bizUserId, $data['order_sn'], $code);
             if ($res['status'] != 'OK') {
                 outPutData('', $res['message'], Config::get('code.tipsCode'));
             }
             $res = array('msg' => '下单成功');
             outPutData($res);
         }

     }

    /**
     * 获取订单信息
     * @param Request $request
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getOrderInfo(Request $request){
        $orModel = new Orders();
        $user_info = $request->user_info;
        $param = $request->param();
        if($request->isPost()) {
            if(empty($param['order_id'])){
                outPutData('','提交参数错误,请重新刷新页面',Config::get('code.tipsCode'));
            }
            $order_data = $orModel->where(array('id'=>intval($param['order_id']),'uid'=> $user_info['id']))->find();
            $order_info = empty($order_data)?array():$order_data->toArray();
            if(empty($order_data)){
                outPutData('','未查询到订单信息',Config::get('code.tipsCode'));
            }
            $order_info['order_time'] = strtotime($order_info['create_time']);
            $order_info['current_time'] = time();
            $order_info['mobile'] = $user_info['mobile'];
            $res['order_info'] = $order_info;
            outPutData($res);
        }


    }

}
